package cocurrency.queue;

import java.util.LinkedList;

/**
 * Created by luzl on 4/7/2017.
 */
public class MyNativeQueue {
    private LinkedList<String> content=new LinkedList<>();
    private final int length=10;

    public synchronized void put(String message){
        if(content.size()>=length){
            //queue is full, can not put more, block
            try {
                System.out.println("can't put more, blocking ...");
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        content.addFirst(message);
        notify();
    }

    public synchronized String get(){
        if (content.size()==0){
            //queue is full, can not put more, block
            try {
                System.out.println("no message now, blocking ...");
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        String message=content.getLast();
        content.removeLast();
        notify();
        return message;
    }

    public static void main(String[] args){
        MyNativeQueue queue=new MyNativeQueue();

        new Thread(new Runnable() {
            @Override
            public void run() {
                int i=0;
                while(true) {
                    i++;
                    queue.put(i+"");
                    try {
                        Thread.currentThread().sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                while(true) {
                    String message=queue.get();
                    try {
                        Thread.currentThread().sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("get message=>"+message);
                }
            }
        }).start();
    }
}
